package com.shengyin.ec.security;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.RequestKey;
import org.springframework.security.web.util.UrlMatcher;
import org.springframework.stereotype.Component;

import com.shengyin.ec.model.entity.Resources;
import com.shengyin.ec.service.permission.ResourcesService;

@Component("resourceDetailsBuilder")
public class ResourceDetailsBuilder {

	@javax.annotation.Resource
	ResourcesService resourceService;

    public FilterInvocationSecurityMetadataSource createUrlSource(UrlMatcher urlMatcher) {
        return new DefaultFilterInvocationSecurityMetadataSource(urlMatcher,
            this.buildRequestMap());
    }


    protected LinkedHashMap<RequestKey, Collection<ConfigAttribute>> buildRequestMap() {
        LinkedHashMap<RequestKey,  Collection<ConfigAttribute>> requestMap = null;
        requestMap = new LinkedHashMap<RequestKey,  Collection<ConfigAttribute>>();


        Map<String, String> resourceMap = this.findResources();

        for (Entry<String, String> entry : resourceMap.entrySet()) {
            RequestKey key = new RequestKey(entry.getKey(), null);
            System.out.println(key+"==============");
            requestMap.put(key,
            		SecurityConfig.createListFromCommaDelimitedString(entry.getValue()));
        }

        return requestMap;
    }


    protected Map<String, String> findResources() {

    	List<Resources> resources = resourceService.getResourcesList();
    	System.out.println("============="+resources.size());
        Map<String, String> resourceMap = new LinkedHashMap<String, String>();
        for (Resources resource : resources) {
        
			String  roleString = StringUtils.join(resource.getRolenames(), ",");
			resourceMap.put(resource.getUrl(), roleString);
		}

        return resourceMap;
    }
}
